﻿Option Explicit On
Option Strict On

Imports System.IO

''' <summary>
''' Formulario Principal: Formulario que muestra los datos de citas de hoy, y que permite
''' acceder a las demás funcionalidades del programa
''' </summary>
''' <author>Julio Antoranz</author>

Public Class Principal
    'Variables publicas 
    Private _usuarioPrincipal As Usuario
    Private _database As BBDD


    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        ' creamos las variables
        _database = New BBDD
        _usuarioPrincipal = Login.UsuarioLogin

        'Fecha que se mostrara en la aplicacion
        lbFecha.Text = DateTime.UtcNow.ToString("F")

        'Cargar datos de la tabla
        ActualizarCitas()

        'Cargar datos Notas
        If File.Exists("notas.txt") Then
            'Leemos las notas desde fichero
            Dim ficheroLectura As StreamReader = New StreamReader("notas.txt")
            Dim lineaLectura As String

            'Vaciamos el Richtextbox antes de escribir
            rtbNotas.Clear()

            'Cargamos los datos desde fichero el Richtextbox

            Do
                lineaLectura = ficheroLectura.ReadLine()
                If lineaLectura <> "" Then
                    rtbNotas.Text = rtbNotas.Text + lineaLectura + vbCrLf
                End If
            Loop While lineaLectura <> ""
            ficheroLectura.Close()
        Else
            Dim ficheroEscritura As New StreamWriter("notas.txt")
        End If
    End Sub


    Private Sub btConsultarCitas_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btConsultarCitas.Click
        ConsultaCitas.ShowDialog()
    End Sub


    Private Sub btAñadirCita_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btAñadirCita.Click
        AgregarCita.Show()
    End Sub


    Private Sub bRecordatorio_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bRecordatorio.Click
        AgregarRecordatorio.Show()
    End Sub


    Private Sub btBuscar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btBuscar.Click
        Buscar.Show()
    End Sub


    Private Sub CopiaDeSeguridadToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopiaDeSeguridadToolStripMenuItem.Click
        If sfdCopiaSeguridad.ShowDialog = Windows.Forms.DialogResult.OK Then
            File.Copy("Database1.accdb", sfdCopiaSeguridad.FileName, True)
        End If
    End Sub


    Private Sub btCobro_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btCobro.Click
        AbrirFactura()
    End Sub


    Private Sub AñadirToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AñadirToolStripMenuItem.Click
        AgregarCita.Show()
    End Sub


    Private Sub ConsultarToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConsultarToolStripMenuItem.Click
        ConsultaCitas.Show()
    End Sub


    Private Sub CobroToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CobroToolStripMenuItem.Click
        btFacturar.Show()
    End Sub


    Private Sub guardarNotas()
        'Cuando cerramos la aplicacion escribimos las notas desde fichero
        Dim ficheroSalida As StreamWriter
        ficheroSalida = New StreamWriter("notas.txt")

        ficheroSalida.WriteLine(rtbNotas.Text)

        ficheroSalida.Close()
    End Sub


    Private Sub SalirToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SalirToolStripMenuItem.Click

        Me.Close()
    End Sub


    Private Sub RecordatoriosToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RecordatoriosToolStripMenuItem.Click
        AbrirRecordatorio()
    End Sub


    Private Sub BuscarToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BuscarToolStripMenuItem.Click
        Buscar.Show()
    End Sub


    Private Sub AcercaDeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AcercaDeToolStripMenuItem.Click
        AcercaDe.ShowDialog()
    End Sub


    Private Sub AgregarToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AgregarToolStripMenuItem.Click
        AltaCliente.ShowDialog()
    End Sub


    Private Sub BorrarToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BorrarToolStripMenuItem.Click
        BorrarCita.ShowDialog()
    End Sub


    Private Sub EliminarToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EliminarToolStripMenuItem.Click
        BajaCliente.ShowDialog()
    End Sub


    Private Sub ModificarToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ModificarToolStripMenuItem1.Click
        ModificarCliente.ShowDialog()
    End Sub


    Private Sub dgvCitasUsuario_CellDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvCitasUsuario.CellDoubleClick
        AbrirRecordatorio()
    End Sub


    Private Sub Principal_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        guardarNotas()

        ' si no ha cerrado sesión se cierra el programa
        If Not Login.Visible Then
            Login.Close()
        End If
    End Sub


    Public Sub ActualizarCitas()
        'Borramos todas las filas antes de recargar
        dgvCitasUsuario.Rows.Clear()


        ' comprobamos que el usuario sea correcto
        If _usuarioPrincipal.Codigo > 0 Then

            Dim listaCitas As List(Of Cita)
            Dim client As Cliente
            Dim service As List(Of Servicio)
            Dim conceptos As String
            Dim primerConcepto As Boolean
            Dim recordator As String

            Try

                'Conectamos a la BBDD
                _database.Conectar()

                ' obtenemos las citas de hoy"
                listaCitas = _database.ListaCitas("SELECT * from cita where cod_empleado = " & _usuarioPrincipal.Codigo & _
                                                  " and fecha >= #" & DateTime.UtcNow.ToString("MM/dd/yyyy") & "# " & _
                                                  " and fecha < #" & DateTime.UtcNow.AddDays(1).ToString("MM/dd/yyyy") & "# " & _
                                                  "order by fecha")

                For Each cita As Cita In listaCitas

                    ' obtenemos los datos de la cita
                    primerConcepto = True
                    conceptos = ""
                    client = _database.DevuelveCliente("Select * from cliente where cod = " & CStr(cita.CodigoCliente) & ";")
                    service = _database.ListaServicios("Select * from servicios where cod in (Select cod_servicio  from " & _
                                                         "concepto where cod_cita = " & cita.Codigo & " )")

                    For Each ServicioUnico As Servicio In service
                        If primerConcepto Then
                            conceptos = ServicioUnico.Nombre
                            primerConcepto = False
                        Else
                            conceptos += ", " & ServicioUnico.Nombre
                        End If
                    Next

                    If cita.Recordatorio = "" Then
                        recordator = "No"
                    Else
                        recordator = "Sí"
                    End If

                    'El orden de las columnas es:
                    ' cod_cliente(no visible), Hora_Cita, Nombre_Cliente, Conceptos, recordatorio
                    dgvCitasUsuario.Rows.Add(cita.Codigo, cita.Fecha.ToString("HH:mm"), client.Nombre, _
                                             conceptos, recordator)
                Next

                'Cerramos la BBDD
                _database.Desconectar()

            Catch ex As Exception
                MsgBox("Hubo un error al conectar la base de datos: " & ex.Message)

            End Try
        End If

    End Sub


    Public ReadOnly Property UsuarioPrincipal As Usuario
        Get
            Return _usuarioPrincipal
        End Get
    End Property


    Private Sub CobrarToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CobrarToolStripMenuItem.Click
        btFacturar.Show()
    End Sub


    Private Sub EliminarToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EliminarToolStripMenuItem1.Click

        If MessageBox.Show("¿Está seguro de borrar de la cita seleccionada?", "Advertencia", MessageBoxButtons.YesNo, _
                           MessageBoxIcon.Warning) = Windows.Forms.DialogResult.Yes Then

            Dim borrarcita As Cita
            borrarcita = New Cita

            borrarcita.Codigo = CInt(dgvCitasUsuario.CurrentRow.Cells(0).Value)
            dgvCitasUsuario.Rows.Remove(dgvCitasUsuario.CurrentRow)

        End If
    End Sub



    Private Sub AñadirToolStripMenuItem1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AñadirToolStripMenuItem1.Click
        InsertarUsuario.Show()
    End Sub


    Private Sub ModificarToolStripMenuItem_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ModificarToolStripMenuItem.Click
        ModificarUsuario.Show()
    End Sub


    Private Sub BorrarToolStripMenuItem1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BorrarToolStripMenuItem1.Click
        BorrarUsuarios.Show()
    End Sub


    Private Sub AgregarToolStripMenuItem1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AgregarToolStripMenuItem1.Click
        AgregarServicio.Show()
    End Sub


    Private Sub RestaurarCopiaDeSeguridadToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RestaurarCopiaDeSeguridadToolStripMenuItem.Click
        If ofRestaurar.ShowDialog = Windows.Forms.DialogResult.OK AndAlso MessageBox.Show("¿Confirma que desea reemplazar los datos actuales con esta copia?", "Advertencia", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = Windows.Forms.DialogResult.Yes Then
            Try
                File.Copy(ofRestaurar.FileName, "database1.accdb", True)
            Catch ex As Exception
                MsgBox("Hubo un error al restaurar la base de datos: " & ex.Message)
            End Try
        End If
    End Sub


    Private Sub CerrarSesiónToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CerrarSesiónToolStripMenuItem.Click

        Login.Visible = True
        Me.Close()
    End Sub


    Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
        lbFecha.Text = DateTime.Now.ToString("F")

    End Sub

    ' Abre el formulario de recordatorio y le pasa el código de la cita
    Private Sub AbrirRecordatorio()
        AgregarRecordatorio.Show()

        If dgvCitasUsuario.SelectedRows.Count > 0 Then
            AgregarRecordatorio.MostrarRecordatorio(CInt(dgvCitasUsuario.CurrentRow.Cells(0).Value))
        End If

    End Sub


    Private Sub MToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles MToolStripMenuItem.Click
        AlterarCita()
    End Sub

    Private Sub ModificarToolStripMenuItem2_Click(sender As System.Object, e As System.EventArgs) Handles ModificarToolStripMenuItem2.Click
        AlterarCita()
    End Sub

    Private Sub AlterarCita()
        ModificarCitas.Show()

        If dgvCitasUsuario.SelectedRows.Count > 0 Then
            ModificarCitas.MostrarCita(CInt(dgvCitasUsuario.CurrentRow.Cells(0).Value))
        End If
    End Sub

    Private Sub AbrirFactura()
        btFacturar.Show()

        If dgvCitasUsuario.SelectedRows.Count > 0 Then
            btFacturar.CrearFactura(CInt(dgvCitasUsuario.CurrentRow.Cells(0).Value))
        End If
    End Sub

End Class